package xtodo

class DateTagLib {

	def dateFromNow = { attrs ->
		def date = attrs.date
		def niceDate = getNiceDate(date)
		out << niceDate
	}


	static String getNiceDate(Date date) {
		def now = new Date()
		def diff = Math.abs(now.time - date.time)

		final long second = 1000
		final long minute = second * 60
		final long hour = minute * 60
		final long day = hour * 24
		final long week = day * 7
		def niceTime
		long calc = 0;
		
		calc = Math.floor(diff / week)
		if (calc) {
			niceTime = date.format('dd-MM-yyyy')
			diff %= week
		}
		calc = Math.floor(diff / day)
		if (!niceTime && calc) {
			niceTime = date.format('EE')
			diff %= day
		}
		calc = Math.floor(diff / hour)
		if (!niceTime && calc) {
			niceTime = date.format('HH:mm')
			diff %= hour
		}
		calc = Math.floor(diff / minute)
		if (!niceTime && calc) {
			niceTime = "$calc minute" + (calc > 1 ? "s " : " ")
			niceTime += (date.time > now.time) ? "from now" : "ago"
		}
		if (!niceTime) {
			niceTime = "now"
		}
		
		return niceTime
	}
}
